package com.dodo.blog.server.impl;

import com.comvai.services.persistence.LowLevel;
import com.comvai.services.persistence.PersistenceManager;
import com.comvai.services.persistence.criteria.Criteria;
import com.comvai.services.persistence.criteria.Order;
import com.dodo.blog.model.BaseEntity;
import com.dodo.blog.request.BasicRequest;
import org.apache.commons.lang.StringUtils;

import java.util.logging.Logger;

/**
 * @author <a href="mailto:pohorelec@comvai.com">Jozef Pohorelec</a>
 */
public abstract class AbstractServiceBean
{
    protected final Logger log = Logger.getLogger( this.getClass().getName() );

    protected PersistenceManager datastore;

    public AbstractServiceBean( @LowLevel PersistenceManager datastore )
    {
        this.datastore = datastore;
    }

    public BaseEntity save( BaseEntity entity )
    {
        if ( entity.getId() == null )
        {
            datastore.persist( entity );
        }
        else
        {
            entity = datastore.merge( entity );
        }

        return entity;
    }

    public void delete( Class<? extends BaseEntity> entityClass, Long id )
    {
        if ( id == null )
        {
            return;
        }

        BaseEntity entity = datastore.find( entityClass, id );

        if ( entity != null )
        {
            datastore.delete( entity );
        }
    }

    public <T> void processCriteria( Criteria<T> criteria, BasicRequest request )
    {
        criteria.setFirstResult( request.getFirstRow() );
        criteria.setMaxResults( request.getMaxRows() );

        for ( BasicRequest.Sort sort : request.getSortList() )
        {
            if ( !StringUtils.isBlank( sort.getOrderBy() ) )
            {
                criteria.addOrderRule( sort.getOrderBy(), Order.valueOf( sort.getOrderDirection().name() ) );
            }
        }
    }
}
